<template>
	<view>
		<u-popup v-model="internalShow" mode="center" border-radius="20" :mask-close-able="true"
			@close="handlePopupClose">
			<view class="upload-wrapper">
				<u-upload ref="uUpload" :header="headers" :action="action" :auto-upload="false" max-count="1"
					:preview-full-image="false" @on-remove="handleRemove"></u-upload>

				<u-button @click="handleSubmit" type="primary" :loading="isUploading" style="margin-top: 30rpx;">
					{{ isUploading ? '上传中...' : '确认上传' }}
				</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		props: {
			show: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				internalShow: this.show,
				tempFilePath: '',
				isUploading: false,
				headers: {
					'token': uni.getStorageSync('token') || '',
				},
				action: "http://localhost:1110/ZHLG/upload/avatar",
				fileList: []
			}
		},
		watch: {
			show(newVal) {
				this.internalShow = newVal;
				if (!newVal) {
					this.resetState();
				}
			}
		},
		methods: {
			handleRemove() {
				this.tempFilePath = '';
			},
			handlePopupClose() {
				this.$emit('update:show', false);
			},
			resetState() {
				this.tempFilePath = '';
				this.isUploading = false;
				this.$refs.uUpload?.clear();
			},
			async handleSubmit() {
				this.tempFilePath = this.$refs.uUpload.lists[0].url;
				if (!this.tempFilePath) {
					uni.showToast({
						title: '请先选择文件',
						icon: 'none'
					});
					return;
				}

				this.isUploading = true;

				try {
					const res = this.$refs.uUpload.upload();
					this.$emit('upload-success', res);
					uni.showToast({
						title: '上传成功',
						icon: 'success'
					});
					this.resetState();
					this.handlePopupClose();
				} catch (error) {
					console.error('上传失败:', error);
					uni.showToast({
						title: error.message || '上传失败',
						icon: 'none',
						duration: 3000
					});
					this.$emit('upload-error', error);
				} finally {
					this.isUploading = false;
				}
			}
		}
	}
</script>

<style scoped>
	.upload-wrapper {
		padding: 40rpx;
		width: 80vw;
		max-width: 600rpx;
	}
</style>